import Vue from "vue";
import Router from "vue-router";
import store from "../store";
import base from "../utils/base.js";
import MainPage from "../layout/index.vue";
import DashBoard from "../views/dashboard.vue";
import DemoList from "../views/demo/demo_list.vue";
import PagenationList from "../views/demo/varied_list/pagenation_list.vue";
import horzontalScrollList from "../views/demo/varied_list/horzontal_scroll_list.vue";
import checkboxList from "../views/demo/varied_list/checkbox_list.vue";
import Login from "../views/login/login.vue";

Vue.use(Router);
const router = new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/login",
      component: Login,
    },
    {
      path: "/",
      component: MainPage,
      redirect: "/dashboard",
      children: [
        {
          path: "/dashboard",
          component: DashBoard,
        },
        {
          path: "/demo_list",
          component: DemoList,
        },
        {
          path: "/pagenation_list",
          component: PagenationList,
        },
        {
          path: "/horzontal_scroll_list",
          component: horzontalScrollList,
        },
        {
          path: "/checkbox_list",
          component: checkboxList,
        },
      ],
    },
  ],
});

//全局前置守卫
router.beforeEach((to, from, next) => {
  //先读取本地state是否保存用户信息
  if (!store.getters.userInfo || !store.getters.token) {
    //从localStorage里读取是否保存了vuex的数据
    var _userInfo = localStorage.getItem(base.userInfo);
    if (_userInfo) {
      store.dispatch("setUserInfo", JSON.parse(_userInfo));
    }
  }
  console.log("11--"+store.getters.token)
  if (to.path != "/login") {
    if(to.path == "/dashboard" && to.redirectedFrom == "/"){
      //重置头部标签
      store.dispatch("resetTags");
      //清空头部标签缓存信息
      localStorage.setItem(base.tags, "");
    } 
    //判断是否缓存用户信息token
    if (store.getters.userInfo && store.getters.token) {
      //打开首页
    } else {
      //打开登录页面
      next("/login");
    }
  }
  next();
});

export default router;
